import network
import time
from umqtt.simple import MQTTClient

# WiFi 配置
SSID = "tplink-1"
PASSWORD = "12345678."

# MQTT 服务器配置
MQTT_SERVER = "broker.emqx.io"  # 公共服务器
MQTT_PORT = 1883
CLIENT_ID = "k230_lushan_" + str(time.time())  # 唯一客户端ID
PUB_TOPIC = "k230/pub"  # 发布主题
SUB_TOPIC = "k230/sub"  # 订阅主题

# 连接WiFi
def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print(f"连接WiFi: {SSID}")
        wlan.connect(SSID, PASSWORD)
        while not wlan.isconnected():
            time.sleep(1)
    print(f"WiFi已连接，IP: {wlan.ifconfig()[0]}")
    return wlan

# MQTT消息回调函数
def mqtt_callback(topic, msg):
    print(f"收到主题: {topic.decode()}")
    print(f"消息内容: {msg.decode()}")
    print("-------------------")

# 连接MQTT服务器并订阅主题
def connect_mqtt():
    client = MQTTClient(CLIENT_ID, MQTT_SERVER, port=MQTT_PORT)
    client.set_callback(mqtt_callback)  # 设置回调
    client.connect()
    client.subscribe(SUB_TOPIC)
    print(f"已连接MQTT服务器，订阅主题: {SUB_TOPIC}")
    return client

# 主逻辑
def main():
    wlan = connect_wifi()
    if not wlan.isconnected():
        print("WiFi连接失败，退出")
        return
    
    client = connect_mqtt()
    last_pub_time = 0
    
    try:
        while True:
            # 检查是否有新消息
            client.check_msg()
            
            # 每5秒发布一条消息
            current_time = time.time()
            if current_time - last_pub_time >= 5:
                msg = f"Hello from K230! Time: {int(current_time)}"
                client.publish(PUB_TOPIC, msg)
                print(f"发布消息到 {PUB_TOPIC}: {msg}")
                last_pub_time = current_time
            
            time.sleep(0.1)
    except Exception as e:
        print(f"错误: {e}")
    finally:
        client.disconnect()
        wlan.disconnect()

if __name__ == "__main__":
    main()